/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.HouseholdBean;
import Model.UserBean;
import dao.HouseholdDAO;
import dao.UserDAO;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 *
 * @author amkreuz
 */
@Named(value = "householdController")
@SessionScoped
public class HouseholdController implements Serializable {

    HouseholdBean bean;

    /**
     * Creates a new instance of HouseholdController
     */
    public HouseholdController() {
        bean = new HouseholdBean();
    }

    public HouseholdBean getBean() {
        return bean;
    }

    public void setBean(HouseholdBean bean) {
        this.bean = bean;
    }

    public String createHousehold() {
        try {
            HouseholdDAO.init();
            HouseholdDAO.createHousehold(bean);
            UserDAO.init();
            UserBean userBean = (UserBean) FacesContext.getCurrentInstance().
                    getExternalContext().getSessionMap().get("userBean");
            userBean.setHouseName(bean.getHouseholdName());
            userBean.setIsAdmin(true);
            UserDAO.save(userBean);
            UserDAO.joinHousehold(userBean);
            HouseholdDAO.terminate();
            UserDAO.terminate();
            return "UserHomePage.xhtml";
        } catch (SQLException ex) {
            try {
                HouseholdDAO.terminate();
                UserDAO.terminate();
            } catch (SQLException ex1) {
                Logger.getLogger(HouseholdController.class.getName()).log(Level.SEVERE, null, ex1);
            }

            Logger.getLogger(HouseholdController.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }

    public String deleteHousehold() 
    {
        try {
            HouseholdDAO.init();
            UserBean ub = (UserBean) FacesContext.getCurrentInstance().
                    getExternalContext().getSessionMap().get("userBean");
            HouseholdDAO.deleteChores(ub.getHouseName());
            HouseholdDAO.deleteHouse(ub);
            HouseholdDAO.terminate();

            ub.setHouseName(null);
            return "JoinCreateHousehold.xhtml";
        } catch (SQLException ex) {
            Logger.getLogger(HouseholdController.class.getName()).log(Level.SEVERE, null, ex);
            FacesContext.getCurrentInstance().addMessage("deleteHousehold", new FacesMessage("Cannot Delete Household"));
            return "";
        }
    }
}
